import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getDoctorList } from "../api/api";
// 异步获取医生列表的分页数据：
export const getDoctorAsync = createAsyncThunk(
  "receiveDoctorListAsync",
  (payload) => {
    //  payload:  {  doctorName,  doctorJob,  doctorSex,  limit,  page,}
    return getDoctorList(payload).then((res) => {
      if (res.code === 0) {
        return res.data;
      }
    });
  }
);

export const doctorSlice = createSlice({
  name: "doctors",
  initialState: {
    loading: false,
    list: [
      {
        did: 1,
        dname: "张三",
      },
    ],
  },
  reducers: {
    // 修改list
    receiveDoctorList: (state, actions) => {
      state.list = actions.payload;
    },
    addList: (state, actions) => {
      // state.list.push(actions.payload);
      //   深拷贝之后，添加数据，在修改state
      let arr = JSON.parse(JSON.stringify(state.list));
      arr.push(actions.payload);
      state.list = arr;
    },
  },
  //   异步actions的监听器的配置：
  extraReducers: {
    // 异步actions的成功状态时执行的逻辑：
    // 监听对应的异步action的执行结果，三种状态和Promise一样。fulfilled时，我们去修改state中的List对象的值。这样就实现更新了。
    [getDoctorAsync.fulfilled](state, actions) {
      state.list = actions.payload;
      state.loading = false;
      console.log("隐藏loading。。。。");
    },
    // 失败的状态
    [getDoctorAsync.rejected](state, actions) {
      // actions : {type, payload}
      alert("请求接口失败");
      state.loading = false;
    },
    // 刚开始发送请求时
    [getDoctorAsync.pending](state, { payload }) {
      state.loading = true;
      console.log("显示loading。。。。");
    },
  },
});

// 公开同步的action；
export const { receiveDoctorList, addList } = doctorSlice.actions;

// 默认公开reducer
export default doctorSlice.reducer;

// 简单的引用类型： {a:1,b:2}, [1,2,34],只需要进行浅克隆
// 复杂的引用类型：{a:[],b:{c:10}}, [{did:1,dname:''},{},{}], 这种必须进行深克隆。
